﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Reflection;
using System.Runtime.Loader;

namespace RQX.Common.Web.Web.Container
{
    public static class IocServiceExtension
    {
        /// <summary>
        /// 用于将IocInjection标签的类注入到service中
        /// </summary>
        /// <param name="services"></param>
        public static void AddIocAttributeServices(this IServiceCollection services)
        {
            var pathFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "RQX.Common.Web.Web.*.dll", SearchOption.AllDirectories);

            for (int i = 0; i < pathFiles.Length; i++)
            {
                using (var fs = new FileStream(pathFiles[i], FileMode.Open, FileAccess.Read))
                {
                    var assembly = new AssemblyLoadContext(Guid.NewGuid().ToString("N"), true).LoadFromStream(fs);
                    foreach (var type in assembly.GetTypes())
                    {
                        var serviceAttribute = type.GetCustomAttribute<IocInjectionAttribute>();

                        if (serviceAttribute != null)
                        {
                            switch (serviceAttribute.ServiceLifeTime)
                            {
                                case ServiceLifetime.Singleton:
                                    services.AddSingleton(type);
                                    break;
                                case ServiceLifetime.Scoped:
                                    services.AddScoped(type);
                                    break;
                                case ServiceLifetime.Transient:
                                    services.AddTransient(type);
                                    break;
                            }
                        }
                    }
                }
            }

        }
    }
}
